/*
 * @Description: 开放字段内容标题组件
 * @Author: Rfan
 * @Date: 2022-08-22 19:29:51
 * @LastEditTime: 2023-01-12 16:25:46
 */
import { useMemo, useState } from 'react';
import { Button, Space } from 'antd';
import classNames from 'classnames/bind';
import { useOpeningContext } from '../contexts/OpeningContext';
import AddDialog from './dialogs/AddDialog';
import styles from '../styles/list.module.scss';
import { EnumSortTypes } from '@/view/system/Opening/dictionaries';

const cx = classNames.bind(styles);

interface IContentTitleProps {
  title: string;
  type: number;
}

function ContentTitle(props: IContentTitleProps) {
  const { title, type } = props;
  const {
    list,
    retrieveList,
    sortType,
    selectLevel,
    selectItems,
    updateOpeningSortFunc,
    deleteOpeningFunc
  } = useOpeningContext();

  // 新增弹窗展示状态
  const [saveBtnLoading, setSaveBtnLoading] = useState(false);
  // 新增弹窗展示状态
  const [addDialogVisible, setAddDialogVisible] = useState(false);

  /**
   * @description: 新增开放字段
   */
  const showDialog = (): void => {
    setAddDialogVisible(true);
  };

  /**
   * @description: 保存排序
   */
  const saveSort = () => {
    setSaveBtnLoading(true);
    const currentList = sortType === EnumSortTypes.Normal ? list : retrieveList;
    const sortRule = currentList.map((item: any, idx: number) => {
      const ele: any = item.rule;
      ele.sortNo = idx + 1;
      return ele;
    });
    updateOpeningSortFunc(sortRule).finally(() => {
      setSaveBtnLoading(false);
    });
  };

  return (
    <>
      <div className={cx('sort-header')}>
        <div className={cx('title')}>{title}排序</div>
        <div className={cx('operate')}>
          <Space>
            <Button
              disabled={!selectLevel || JSON.stringify(selectLevel) === '{}'}
              onClick={showDialog}
            >
              新建开放字段
            </Button>
            <Button
              disabled={selectItems.length <= 0}
              onClick={() => {
                deleteOpeningFunc(selectItems);
              }}
            >
              删除开放字段
            </Button>
            <Button type="primary" loading={saveBtnLoading} onClick={saveSort}>
              保存排序
            </Button>
          </Space>
        </div>
      </div>

      {/* 添加开放字段弹窗 */}
      {useMemo(
        () => (
          <AddDialog
            visible={addDialogVisible}
            type={type}
            onClose={() => {
              setAddDialogVisible(false);
            }}
          />
        ),
        [addDialogVisible]
      )}
    </>
  );
}

export default ContentTitle;
